<script lang="ts" setup>
import useCategoryStore from "../../../store/modules/category.ts";
import type {HasSaleAttr, SaleAttr, SpuData, SpuImg, Trademark} from "../../../api/product/spu/type.ts";
import {computed, ref, nextTick} from 'vue'
import {Plus} from '@element-plus/icons-vue'
import {ElMessage} from 'element-plus'

import type {UploadProps} from 'element-plus'
import {reqAddOrUpdateSpu} from "../../../api/product/spu";
import {reqAllSaleAttr, reqAllTradeMark, reqSpuHasSaleAttr, reqSpuImageList} from "../../../api/product/spu";
//接受父组件传过来的自定义事件,用来返回上一场景
const emits = defineEmits(["backPage"]);

const categoryStore = useCategoryStore();//获取仓库实例
//spu的数据
let spuParams = ref<SpuData>({
  category3Id: '', //收集三级分类的ID
  spuName: '', //SPU的名字
  description: '', //SPU的描述
  tmId: '', //品牌的ID
  spuImageList: [],
  spuSaleAttrList: [],
})

//保存请求过来的数据
const tradeMark = ref<Trademark[]>([]);//品牌
const imageList = ref<SpuImg[]>([]);//图片
const allSaleAttr = ref<HasSaleAttr[]>([]);//全部的销售属性
const hasSaleAttr = ref<SaleAttr[]>([]);//已有的销售属性

//收集销售属性的ID与属性值的名字
let saleAttrIdAndValueName = ref<string>('')

//利用父组件获取基础信息，品牌，和所有销售属性
const initAddSpu = async () => {
  //清空数据
  spuParams.value = {
    category3Id: '', //收集三级分类的ID
    spuName: '', //SPU的名字
    description: '', //SPU的描述
    tmId: '', //品牌的ID
    spuImageList: [],
    spuSaleAttrList: [],
  };

  imageList.value = [];
  saleAttrIdAndValueName.value = '';
  hasSaleAttr.value = [];

  //发起请求
  const requst1 = await reqAllTradeMark();
  const requst3 = await reqAllSaleAttr();
  tradeMark.value = requst1.data;
  allSaleAttr.value = requst3.data;

  //获取三级分类id
  spuParams.value.category3Id = categoryStore.c3Id as number
}

//根据利用父组件获取spuId
const reqAll = async (spu: SpuData) => {
  // 获取分类ID
  spuParams.value.category3Id = categoryStore.c3Id as number

  const requst1 = await reqAllTradeMark();
  const requst2 = await reqSpuImageList(spu.id);
  const requst3 = await reqAllSaleAttr();
  const requst4 = await reqSpuHasSaleAttr(spu.id);

  tradeMark.value = requst1.data;
  imageList.value = requst2.data.map(item => {
    return {
      name: item.imageName,
      url: item.imageUrl,
      id: item.id,
      spuId: item.spuId
    } as SpuImg
  });
  allSaleAttr.value = requst3.data;
  hasSaleAttr.value = requst4.data;
  // ?
  spuParams.value = spu;
}

//获取没有的销售属性
let unSelectSaleAttr = computed(() => {
  return allSaleAttr.value.filter(item => {
    return hasSaleAttr.value.every(item1 => {
      return item.saleAttrName !== item1.saleAttrName;
    });
  });
});

defineExpose({reqAll, initAddSpu});

//保存数据
const save = async () => {
  //整理图片数据
  spuParams.value.spuImageList = imageList.value.map((item: any) => {
    return {
      imageName: item.name,
      imageUrl: (item.response && item.response.data) || item.url
    }
  })
  //整理销售属性
  spuParams.value.spuSaleAttrList = hasSaleAttr.value
  //添加SPU的ID
  spuParams.value.category3Id = categoryStore.c3Id as number
  //发请求
  let result = await reqAddOrUpdateSpu(spuParams.value)
  if (result.code === 200) {
    ElMessage({ type: 'success', message: '保存成功' })
    emits('backPage', spuParams.value.id)
  } else {
    ElMessage({ type: 'error', message: '保存失败' })
  }
}


const dialogImageUrl = ref('');//收集图片数据
const dialogVisible = ref(false); //控制大图预览

//图片删除前钩子，可以做些什么
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

//打开图片预览，固定格式
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

//图片上传前判断一下
const handleUpload = (file: any) => {
  if (
      file.type === "image/png" ||
      file.type === "image/jpeg" ||
      file.type === "image/gif" ||
      file.type === "image/webp"
  ) {
    if (file.size / 1024 / 1024 < 3) {
      return true;
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件务必小于3M',
      })
      return false;
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件务必PNG|JPG|GIF',
    })
    return false
  }
}

//添加销售属性
const addSaleAttr = () => {
  //分割字符串
  const [id, name] = saleAttrIdAndValueName.value.split(':')
  //添加到已有销售属性
  hasSaleAttr.value.push({
    baseSaleAttrId: id,
    saleAttrName: name,
    spuSaleAttrValueList: []
  })
  //清空选择
  saleAttrIdAndValueName.value = ''
}

//编辑属性值
const toEdit = (row: SaleAttr) => {
  row.flag = true;
  // 添加nextTick确保DOM更新后再聚焦
  nextTick(() => {
    const inputElement = document.querySelector(`#sale-attr-input-${row.baseSaleAttrId}`) as HTMLInputElement;
    if (inputElement) {
      inputElement.focus();
    }
  });
}

//属性值输入框失焦该做什么
const toLook = (row: SaleAttr) => {
  // 确保 row.saleAttrValue 存在再调用 trim()
  if (!row.saleAttrValue || (row.saleAttrValue as string).trim() === "") {
    ElMessage({
      type: "warning",
      message: "怎么能是空呢"
    });
    row.flag = false;
    return;
  }

  if (row.spuSaleAttrValueList.find(item => item.saleAttrValueName === row.saleAttrValue)) {
    ElMessage({
      type: "warning",
      message: "怎么能重复呢"
    });
    row.saleAttrValue = "";
    row.flag = false;
    return;
  }

  row.spuSaleAttrValueList.push({
    saleAttrId: row.baseSaleAttrId,
    saleAttrValueName: row.saleAttrValue as string
  });

  //给数据清空
  row.saleAttrValue = '';
  row.flag = false;
}

// 添加回车事件处理函数
const handleEnter = (row: SaleAttr) => {
  toLook(row);
}
</script>

<template>
  <el-form>
    <!--    SPU名称-->
    <el-form-item label="SPU名称">
      <template #default>
        <el-input v-model="spuParams.spuName" placeholder="输入spu名称"></el-input>
      </template>
    </el-form-item>
    <!--    SPU品牌-->
    <el-form-item label="SPU品牌">
      <el-select v-model="spuParams.tmId">
        <el-option v-for="(item) in tradeMark" :key="item.id" :label="item.tmName" :value="item.id"></el-option>
      </el-select>
    </el-form-item>
    <!--    SPU描述-->
    <el-form-item label="SPU描述">
      <el-input v-model="spuParams.description" placeholder="spu的描述" type="textarea"></el-input>
    </el-form-item>
    <!--    SPU图片-->
    <el-form-item label="SPU图片">
      <el-upload
          v-model:file-list="imageList"
          :before-upload="handleUpload"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          action="/api/admin/product/fileUpload"
          list-type="picture-card"
      >
        <el-icon>
          <Plus/>
        </el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img :src="dialogImageUrl" alt="Preview Image" style="width: 400px; height: 400px;"/>
      </el-dialog>
    </el-form-item>
    <!--    SPU销售属性-->
    <el-form-item label="SPU销售属性">
      <el-select v-model="saleAttrIdAndValueName" style="width: 240px; margin-right: 10px"
                 :placeholder="unSelectSaleAttr.length ? `还有${unSelectSaleAttr.length}可选` : `无`">
        <el-option v-for="item in unSelectSaleAttr" :key="item.id" :label="item.saleAttrName"
                   :value="`${item.id}:${item.saleAttrName}`"></el-option>
      </el-select>
      <el-button :disabled="!saleAttrIdAndValueName" @click="addSaleAttr" icon="Plus" style="margin: 10px 0" type="primary">添加属性</el-button>
      <!--      展示销售属性-->
      <el-table :data="hasSaleAttr" border>
        <el-table-column align="center" label="序号" type="index" width="80px"></el-table-column>
        <el-table-column label="销售属性名称" prop="saleAttrName" width="120px"></el-table-column>
        <el-table-column label="销售属性值" >
          <template #default="{row}">
            <el-tag v-for="(item, index) in row.spuSaleAttrValueList" :key="index" class="mx-1"
                    closable
                    style="margin: 0 5px" @close="row.spuSaleAttrValueList.splice(index, 1)">
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-input 
              @blur="toLook(row)" 
              @keydown.enter="handleEnter(row)"
              v-model="row.saleAttrValue" 
              v-if="row.flag === true" 
              placeholder="输入属性名" 
              style="width: 120px" 
              size="small"
              :id="`sale-attr-input-${row.baseSaleAttrId}`">
            </el-input>
            <el-button @click="toEdit(row)" v-else icon="Plus" label="操作" type="primary" size="small"></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px">
          <template #default="{$index}">
            <el-button icon="Delete" type="danger" @click="hasSaleAttr.splice($index, 1)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <!--    修改-->
    <el-form-item label="修改">
      <el-button type="primary" @click="save" :disabled="hasSaleAttr.length === 0">保存</el-button>
      <el-button type="danger" @click="emits('backPage', spuParams.id)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<style lang="scss" scoped>

</style>